package com.youboy.oauth.provider;

import com.youboy.oauth.common.OAuthException;
import com.youboy.oauth.common.OAuthParameters;
import com.youboy.oauth.consumer.OAuthConsumerService;
import com.youboy.oauth.model.OAuthRequest;
import com.youboy.oauth.nonce.OAuthNonceService;
import com.youboy.oauth.provider.impl.OAuth10aProvider;
import com.youboy.oauth.signature.OAuthSignatureFactory;
import com.youboy.oauth.token.OAuthTokenService;

/**
 * 
 * @author loudyn
 * 
 */
public class OAuthProviderBuilder {
	private OAuthRequest request;
	private OAuthConsumerService consumerService;
	private OAuthTokenService tokenService;
	private OAuthNonceService nonceService;
	private OAuthSignatureFactory signatureFactory;

	/**
	 * 
	 * @param oauthRequest
	 * @return
	 */
	public OAuthProviderBuilder provide(OAuthRequest oauthRequest) {
		this.request = oauthRequest;
		return this;
	}

	/**
	 * 
	 * @param oauthConsumerService
	 * @return
	 */
	public OAuthProviderBuilder withOAuthConsumerService(OAuthConsumerService oauthConsumerService) {
		this.consumerService = oauthConsumerService;
		return this;
	}

	/**
	 * 
	 * @param oauthTokenService
	 * @return
	 */
	public OAuthProviderBuilder withOAuthTokenService(OAuthTokenService oauthTokenService) {
		this.tokenService = oauthTokenService;
		return this;
	}

	/**
	 * 
	 * @param oauthNonceService
	 * @return
	 */
	public OAuthProviderBuilder withOAuthNonceService(OAuthNonceService oauthNonceService) {
		this.nonceService = oauthNonceService;
		return this;
	}

	/**
	 * 
	 * @param oauthSignatureFactory
	 * @return
	 */
	public OAuthProviderBuilder withOAuthSignatureFactory(OAuthSignatureFactory oauthSignatureFactory) {
		this.signatureFactory = oauthSignatureFactory;
		return this;
	}

	/**
	 * 
	 * @return
	 * @throws OAuthException
	 */
	public OAuthProvider build() throws OAuthException {
		String oauthVersion = this.request.getOAuthParameters().get(OAuthParameters.OAUTH_VERSION.asString());

		if (OAuth10aProvider.SUPPORT_OAUTH_VERSION.equals(oauthVersion)) {
			return new OAuth10aProvider(request, consumerService, tokenService, nonceService, signatureFactory);
		}
		
		throw new OAuthException(String.format("Can't build a OAuthProvider with oauthVersion=%s", oauthVersion));
	}
}
